import { Router } from "express";
import multer from "multer";

const r = Router();

// 配置 multer 用于处理文件上传
const upload = multer({
  storage: multer.memoryStorage(),
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB
  }
});

// 人脸注册 - 支持 FormData
r.post("/register", upload.single('image'), (req, res) => {
  console.log("[liveness] 收到注册请求，Content-Type:", req.get('Content-Type'));
  console.log("[liveness] req.body:", req.body);
  console.log("[liveness] req.file:", req.file ? 'File received' : 'No file');
  
  // 从 FormData 中获取参数
  const userId = req.body.person_id || req.body.userId;
  const personName = req.body.person_name || req.body.username;
  const imageFile = req.file;
  
  if (!userId || !imageFile) {
    return res.status(400).json({ 
      error: "缺少必要参数", 
      code: "MISSING_PARAMS",
      received: { 
        userId: !!userId, 
        personName: !!personName,
        imageFile: !!imageFile 
      }
    });
  }

  // 模拟人脸注册处理
  console.log(`[liveness] 注册用户 ${userId} (${personName}) 的人脸信息`);
  console.log(`[liveness] 图片大小: ${imageFile.size} bytes`);
  
  res.json({
    success: true,
    message: "人脸注册成功",
    faceId: `face_${userId}_${Date.now()}`,
    userId,
    personName
  });
});

// 活体检测验证 - 支持 FormData
r.post("/verify", upload.single('file'), (req, res) => {
  console.log("[liveness] 收到验证请求，Content-Type:", req.get('Content-Type'));
  console.log("[liveness] req.body:", req.body);
  console.log("[liveness] req.file:", req.file ? 'File received' : 'No file');
  
  // 从 FormData 中获取参数
  const userId = req.body.user_id || req.body.userId;
  const imageFile = req.file;
  const action = req.body.action;
  
  if (!userId || !imageFile) {
    return res.status(400).json({ 
      error: "缺少必要参数", 
      code: "MISSING_PARAMS",
      received: { userId: !!userId, imageFile: !!imageFile, action: !!action }
    });
  }

  // 模拟活体检测处理
  console.log(`[liveness] 验证用户 ${userId} 的活体检测，动作: ${action}`);
  console.log(`[liveness] 图片大小: ${imageFile.size} bytes`);
  
  // 模拟验证结果（90%概率成功）
  const isValid = Math.random() > 0.1;
  const confidence = 0.85 + Math.random() * 0.14; // 85-99%置信度
  
  if (isValid) {
    res.json({
      success: true,
      message: "活体检测通过",
      confidence: parseFloat(confidence.toFixed(2)),
      userId,
      timestamp: new Date().toISOString()
    });
  } else {
    res.status(400).json({
      success: false,
      error: "活体检测失败",
      code: "LIVENESS_FAILED",
      confidence: parseFloat((confidence * 0.6).toFixed(2))
    });
  }
});

// 获取用户已注册的人脸信息
r.get("/faces/:userId", (req, res) => {
  const { userId } = req.params;
  
  console.log(`[liveness] 获取用户 ${userId} 的人脸信息`);
  
  res.json({
    userId,
    faces: [
      {
        faceId: `face_${userId}_demo`,
        registeredAt: new Date(Date.now() - 86400000).toISOString(), // 1天前
        status: "active"
      }
    ],
    total: 1
  });
});

export default r;